class QuaternionTool{
	/* 
	根据,轴,角(度)计算四元数.
	@param aixs:轴
	@param thetaInDegree:角度
	@return Quaternion
	用例:
		var angle:float = 0;
		function Update () {
			if(Input.GetButton("Fire1")){
				angle ++;
				transform.rotation = QuaternionTool.AxisAngle(Vector3.up,angle);
			}
		}
	*/
	static function AxisAngle(axis:Vector3,thetaInDegree:float):Quaternion{
		//半角,弧度
		var a:float = thetaInDegree / 2 * Mathf.Deg2Rad;
		var n:Vector3 = axis * Mathf.Sin(a);
		var w:float = Mathf.Cos(a);
		return Quaternion(n.x,n.y,n.z,w);
	}
	/**
	屏幕到世界的旋转,无碰撞检测.
	@param camera
	用例:
		var cam:Camera;
		var Bullet:GameObject;
		function Update () {
			if(Input.GetButtonDown("Fire1")){
				var q:Quaternion = QuaternionTool.Screen2World(cam);
				var bullet:GameObject = Instantiate(Bullet,cam.transform.position,q);
					bullet.rigidbody.AddForce(bullet.transform.forward * 1000);
			}
		}
	*/
	static function Screen2World(cam:Camera):Quaternion{
		var ray:Ray = cam.ScreenPointToRay(Input.mousePosition);
		return Quaternion.FromToRotation(Vector3.forward,ray.direction);
	}
	/**
	屏幕到世界的旋转,当碰撞到某物体时返回q,否则返回单位q.
	*/
	static function Screen2WorldWhenHit(cam:Camera):Quaternion{
		var ray:Ray = cam.ScreenPointToRay(Input.mousePosition);
		if(Physics.Raycast(ray)){
			return Quaternion.FromToRotation(Vector3.forward,ray.direction);
		}
		return Quaternion.identity;
	}
	/**
	转换为4x4矩阵.
	*/
	static function ToMatrix4x4(q:Quaternion):Matrix4x4{
		var x:float = q.x;
		var x2:float = x * x;
		var y:float = q.y;
		var y2:float = y * y;
		var z:float = q.z;
		var z2:float = z * z;
		var w:float = q.w;
		
		var m:Matrix4x4 = Matrix4x4.identity;
			m.SetRow(0,Vector4(1-2*y2-2*z2,2*x*y+2*w*z,2*x*z-2*w*y,0));
			m.SetRow(1,Vector4(2*x*y-2*w*z,1-2*x2-2*z2,2*y*z+2*w*z,0));
			m.SetRow(2,Vector4(2*x*z+2*w*y,2*y*z-2*w*x,1-2*x2-2*y2,0));
			m.SetRow(3,Vector4(0,0,0,1));
		return m;
	}
}